package ue.client.networking;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Arrays;

import javax.swing.JOptionPane;

public class Client {
	protected String ip;
	protected int port;
	
	protected Socket socket;
	
	protected Thread inThread;
	protected ClientInputListener in;
	protected DataOutputStream out;
	
	protected String name;
	protected String password;
	
	protected boolean identified;

	public Client(String ip, int port, String name, String password) {
		try {
			socket = new Socket(ip, port);
			out = new DataOutputStream(socket.getOutputStream());
			out.flush();
			in = new ClientInputListener(new DataInputStream(socket.getInputStream()), this);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, "Server not found.", "Unable to connect", JOptionPane.ERROR_MESSAGE);
			System.exit(1);
		}
		
		this.name = name;
		this.password = password;
		
		identified = false;
		
		inThread = new Thread(in);
		inThread.start();
//		in.run();
	}
	
	protected void sendCommand(byte command) {
		try {
			out.write(new byte[] { command });
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(1);
		}
	}
	
	protected void sendBigInteger(BigInteger n) {
		try {
			out.write(Arrays.copyOf(n.toByteArray(), 64));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void requestLocation(int x, int y) {
		try {
			out.write(new byte[] { 1 });
			out.writeInt(x);
			out.writeInt(y);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
	
	public boolean isIdentified() {
		return identified;
	}
}
